package com.zhanggm.cart.controller;

import cn.hutool.jwt.JWTUtil;
import com.zhanggm.cart.feign.ProductService;
import com.zhanggm.cart.feign.TM4Product;
import com.zhanggm.cart.pojo.CartPojo;
import com.zhanggm.zyk.contract.config.AjaxResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/cart/")
public class CartController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;

    @Autowired
    ProductService productService;


    /**
     * 添加购物车
     * @param productId
     * @param num
     * @return
     */
    @GetMapping("add")
    public AjaxResult add(String productId, Integer num) {
        Object userId = JWTUtil.parseToken(request.getHeader("token")).getPayload("id");
        redisTemplate.opsForHash().put("cart:" + userId, productId, num);
        return AjaxResult.success();
    }

    @PostMapping("postAdd")
    public AjaxResult postAdd(@RequestBody CartPojo cartPojo) {
        Object userId = JWTUtil.parseToken(request.getHeader("token")).getPayload("id");
        redisTemplate.opsForHash().put("cart:" + userId, cartPojo.getProductId(), cartPojo.getNum());
        return AjaxResult.success();
    }

    /**
     * 我的购物车
     * @return
     */
    @GetMapping("my")
    public AjaxResult my() {
        //当前登录用户
        Object userId = JWTUtil.parseToken(request.getHeader("token")).getPayload("id");
        //购物车数据
        Map<String, Integer> cartMap = redisTemplate.opsForHash().entries("cart:" + userId);
        Set<String> productIdSet = cartMap.keySet();
        //远程调用查询商品的信息
        List<TM4Product> productList = productService.getListByIds(productIdSet);
        BigDecimal total = new BigDecimal("0");
        for (TM4Product product : productList) {
            product.setNum(cartMap.get(product.getId()+""));
            product.setTotal(product.getPrice().multiply(new BigDecimal(product.getNum() + "")));
            total = total.add(product.getTotal());
        }
        //封装返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("productList", productList);
        resultMap.put("total", total);

        return AjaxResult.success(resultMap);

    }


}
